package com.rongsoft.chain.interceptor;

import com.rongsoft.chain.executor.CommandExecutor;
import com.rongsoft.chain.executor.CommandExecutorImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class AbstractEngineConfiguration {

    protected List<CommandInterceptor> commandInterceptors;

    protected CommandExecutor commandExecutor;

    public void initCommandInterceptors() {
        if (commandInterceptors == null) {
            commandInterceptors = new ArrayList<>();
            commandInterceptors.add(new LogInterceptor());
            commandInterceptors.add(new BizCheckInterceptor());
            commandInterceptors.add(new TransactionInterceptor());
            commandInterceptors.add(new CommandInvoker());
        }
    }

    public void initCommandExecutor() {
        if (commandExecutor == null) {
            if (CollectionUtils.isEmpty(commandInterceptors)){
                initCommandInterceptors();
            }
            CommandInterceptor first = initInterceptorChain(commandInterceptors);
            commandExecutor = new CommandExecutorImpl(first);
        }
    }

    public CommandInterceptor initInterceptorChain(List<CommandInterceptor> chain) {
        if (chain == null || chain.isEmpty()) {
            log.error("invalid command interceptor chain configuration: " + chain);
        }
        for (int i = 0; i < chain.size() - 1; i++) {
            chain.get(i).setNext(chain.get(i + 1));
        }
        return chain.get(0);
    }


    public CommandExecutor getExecutorChain(){
        if (commandExecutor == null){
            initCommandExecutor();
        }
        return commandExecutor;
    }


}
